<template>
  <div class="container">
      <a-page-header
          title="病人信息管理"
        />
      <div class="condition-container">
        
        <p class="title">Operation：</p>
        <div class="condition-btn-group">
          <!-- <a-button type="primary"> 新增 </a-button> -->
          <!-- 用户名查找 -->
          用户名：
          <a-input placeholder="搜索用户名" allow-clear @change="onChangeUsername" v-model='searchUsername' style="width:200px"/>
          <!-- 主治医生查找 -->
          <!-- 主治医生：
          <a-input placeholder="搜索主治医生" allow-clear @change="onChangeDoctor" v-model='doctorUsername' style="width:200px"/> -->
          <!-- 检查时间查找 -->
          <!-- 检查时间：
          <a-range-picker @change="onChangeCheckDate"   style="width:200px"/> -->
          <!-- 检查时间查找 -->
          <!-- 治疗结束时间：
          <a-range-picker @change="onChangeFinishedDate"   style="width:200px"/> -->
        </div>
      </div>

      <!-- 系统用户管理，查看用户列表，审核激活注册信息 -->
      <a-table :columns="columns" :data-source="data" class="table-container">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <!-- <span slot="customTitle"><a-icon type="smile-o" /> 用户名</span> -->
        <span slot="tag" slot-scope="tag">
        <a-tag
            :color="tag === false ? 'red' : 'green'"
        >
            {{ tag }}
        </a-tag>
        </span>
        <span slot="action" slot-scope="record">
            <!-- {{record}} -->
            <a-button type="link"  @click="showModal(record)">查询病人过往病史</a-button>
            &nbsp;&nbsp;
            <a-button type="link"  @click="exportCaseReport(record)">病人病史导出</a-button>
            <!-- <a-button type="link"  @click="updatePrescription(record)">查询病人过往病史</a-button> -->
            <!-- <a-button type="primary"  @click="activeAccount(record)"> </a-button> -->
        </span>
    </a-table>

    <!-- 病人病史信息 -->
    <!-- 更新权限对话框 -->
     <a-modal v-model="visible" title="病史记录" @ok="handleOk">
       <a-form :form="recordModal">
        <!-- 用户名 -->
        <a-form-item label="患者用户名">
              <a-input
              disabled
                v-decorator="[
                  'username',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者用户名',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
        <!-- 账户地址
        <a-form-item v-bind="formItemLayout" label="患者用户名">
              <a-input
              disabled
                v-decorator="[
                  'accountAddress',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者用户名',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item> -->
        <!-- 病史记录 -->
        <a-form-item label="病史记录" has-feedback >
           <a-list item-layout="horizontal" :data-source="recordData">
            <a-list-item slot="renderItem" slot-scope="item, index">
              <a-card :title="'序号:' + (index)" style="width:100%">
                <!-- {{item}} -->
                <p>病历号：{{item.id}}</p>
                <p>症状：{{item.sympton}}</p>
                <p>病情判定：{{item.judge}}</p>
                <p>检查时间：{{item.checkDate}}</p>
                <p>就诊结束时间：{{item.finishedDate}}</p>
                <p>处方策略：{{item.dealPolicy}}</p>
                <p>合计金额：{{item.price}} (元)</p>
              </a-card>
            </a-list-item>
          </a-list>
        </a-form-item>
       </a-form>

    </a-modal>
  </div>
</template>

<script>
import { findClientInfo } from '@/api/user/user';
import { findClientHistoryInfo } from '@/api/case_info/patient_record';
import JSZipUtils from "jszip-utils";
import JSZip from "pizzip";
import Docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";


const columns = [
  // 患者用户名
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  // 用户电话
  {
    title: '用户电话',
    dataIndex: 'telephone',
    key: 'telephone',
  },
  // 用户邮箱
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  // 用户身份证信息
  {
    title: '身份证号',
    dataIndex: 'identify',
    key: 'identify',
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];


const recordData = [
  // {
  //   id: 1,    // 病历号
  //   sympton: "感冒发烧",   // 症状
  //   judge: "流感",   
  //   checkDate: "2022-4-3 11:45:10",   // 就诊时间
  //   finishedDate: "2022-4-3 11:46:5",     // 就诊结束时间 
  //   dealPolicy: "阿司匹林 1盒 布洛芬颗粒 6包",  // 处方策略
  //   price: 120, // 合计金额
  // },
  // {
  //   id: 2,    // 病历号
  //   sympton: "感冒发烧流鼻涕",   // 症状
  //   judge: "流感",   
  //   checkDate: "2022-4-3 12:12:10",   // 就诊时间
  //   finishedDate: "2022-4-3 12:43:52",     // 就诊结束时间 
  //   dealPolicy: "阿司匹林 1盒",  // 处方策略
  //   price: 30, // 合计金额
  // },
];

export default {
    data(){
        return {
            data: [],
            cacheData: [],
            columns,

            searchUsername: '',
            roleMap: {
              'SYS_ADMIN':'系统管理员',
              'DOCTOR': "医生",
              "CLIENT": "普通用户"
            },
            visible: false,
            formItemLayout: {
              labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
              },
              wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
              },
            },

            // 病史记录
            recordData,
        }
    },
    methods: {
        // activeAccount(record){
        //     console.log("激活账户")
        // },
        // getCredentialsInfo(record){
        //     console.log("查看账户认证信息")
        // },
        findPatientHistory(record){
          console.log(record)
        },
        onChangeUsername(e){
          console.log(this.searchUsername, e)
          this.data = this.cacheData.filter(item=>{
            return item.username.indexOf(this.searchUsername) != -1;
          })
        },
        onChangeCheckDate(date, dateString){
          console.log(date, dateString)
        },
        onChangeFinishedDate(date, dateString){
          console.log(date, dateString)
        },
        onChangeDoctor(e){
          console.log(e)
        },
        showModal(record) {
          this.visible = true;
          this.$nextTick(() => {
          // 加载病人历史记录
          var param = {username: record.username};
          findClientHistoryInfo(param)
          .then(data=>{
            console.log("获取病历信息完成", data);
            var records = data.data;
            this.recordData = []
            for(var i = 0; i < records.length; i++){
              var record = records[i];
              var prescription = record[6][0];
              console.log("prescription:" , prescription);
              var t = {
                id: record[0],    // 病历号
                sympton: record[4],   // 症状
                judge: prescription == undefined ? "" : prescription[2],   
                checkDate: this.$moment(new Date(Number(record[2]))).format('YYYY-MM-DD HH:mm:ss'),   // 就诊时间
                finishedDate: this.$moment(new Date(Number(record[3]))).format('YYYY-MM-DD HH:mm:ss'),     // 就诊结束时间 
                dealPolicy: prescription == undefined ? "" : prescription[3],  // 处方策略
                price: prescription == undefined ? "" : prescription[6], // 合计金额
              }
              this.recordData.push(t);
            }


          }).catch(err=>{
            console.log("获取历史病历出错", err);
          })

          this.recordModal.setFieldsValue({
            username: record.username,
            accountAddress: record.accountAddr,
            role: record.role
          })});
        },
        exportCaseReport(record){
          var param = {username: record.username};
          findClientHistoryInfo(param)
          .then(data=>{
            console.log("获取病历信息完成", data);
            var records = data.data;
            this.recordData = []
            for(var i = 0; i < records.length; i++){
              var record = records[i];
              var prescription = record[6][0];
              console.log("prescription:" , prescription);
              var t = {
                id: record[0],    // 病历号
                sympton: record[4],   // 症状
                judge: prescription == undefined ? "" : prescription[2],   
                checkDate: this.$moment(new Date(Number(record[2]))).format('YYYY-MM-DD HH:mm:ss'),   // 就诊时间
                finishedDate: this.$moment(new Date(Number(record[3]))).format('YYYY-MM-DD HH:mm:ss'),     // 就诊结束时间 
                dealPolicy: prescription === undefined ? "" : prescription[3],  // 处方策略
                price: prescription === undefined ? "" : prescription[6], // 合计金额
              }
              this.recordData.push(t);
            }
            // 导出数据
          var wordData = {
            username: param.username,
            recordList: this.recordData
          }
          JSZipUtils.getBinaryContent('case-report.docx', function(error, content) {
            // 抛出异常
            if (error) {
              throw error
            }
            // 创建一个JSZip实例，内容为模板的内容
            let zip = new JSZip(content)
            // 创建并加载docxtemplater实例对象
            let doc = new Docxtemplater().loadZip(zip)
            // 设置模板变量的值
            console.log(wordData)
            doc.setData({...wordData})
            try {
              // 用模板变量的值替换所有模板变量
              doc.render()
            } catch (error) {
              this.$message.error('导出报表失败')
              throw error
            }

            // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
            let out = doc.getZip().generate({
              type: 'blob',
              mimeType:
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            })
            // 将目标文件对象保存为目标类型的文件，并命名
            saveAs(out, 'report.docx')
          })
          }).catch(err=>{
            console.log("获取历史病历出错", err);
          })
        },
        handleOk(e) {
          console.log(e);
          this.visible = false;
        },
    },
    created(){
      // TODO，获取所有病人信息
      var param = {};
      findClientInfo(param).
      then(
        data=>{
          console.log("获取病人信息完成：", data);
          this.data = data.data;
          this.cacheData = this.data
        }
      ).catch(
        err=>{
          console.log("获取病人信息错误：", err);
        }
      )
    },
    beforeCreate(){
       this.recordModal = this.$form.createForm(this, { name: 'recordModal' });
    }
}
</script>

<style lang="less" scoped>
.container{
    margin: auto;
    width: 90%;
    min-height: 700px;
    // margin-top: 30px;
    margin-bottom: 30px;
    background-color: aliceblue;

}

.table-container{
    min-height: 700px;
}

.condition-container{
  width: 100%;
  min-height: 80px;
  background-color: antiquewhite;
  margin-bottom: 10px;
  padding: 5px;
}

.title{
  font-size: 20px;
  font-weight: bold;
}

.condition-btn-group{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>